#include "../include/server.h"

int mycd3(int sockFd, char *dirname, int ownerID, int curDirID){
    //先判断目录是否合法，如果合法，把路径发给客户端
    //返回当前工作路径的file_id
    char filePath[128] = {0};
    long fileSize = 0;
    char type = 0;
    int queryRet = 0;
    char buf[128] = {0};
    char flag[2] = {0};
    int sendRet = 0;

    /* printf("dirname = %s\n", dirname); */

    if(strcmp(dirname, "..") == 0){
        //跳转到上一层目录
        chdir(dirname);
        getcwd(buf, sizeof(buf));
        sscanf(buf, "/home/albert/netdisk_file%s", filePath);
        if(filePath[0] == 0){
            /* printf("/\n"); */
            filePath[0] = '/';
            flag[0] = 'a';
            sendRet = send(sockFd, flag, 1, 0);
            ERROR_CHECK(sendRet, -1, "send flag");
            send(sockFd, filePath, strlen(filePath), 0);
            return 0;
        }
    }

    else{
        queryRet = query_file(dirname, ownerID, filePath, &fileSize, &type);
        /* printf("ret = %d, ownerID = %d, filePath = %s, type = %c\n", queryRet, ownerID, filePath, type); */
        if(type == 'd'){
            chdir(dirname);
            getcwd(buf, sizeof(buf));
            /* puts(buf); */
            sscanf(buf, "/home/albert/netdisk_file%s", filePath);
            /* puts(filePath); */
            flag[0] = 'a';
            sendRet = send(sockFd, flag, 1, 0);
            ERROR_CHECK(sendRet, -1, "send flag");
            sendRet = send(sockFd, filePath, strlen(filePath), 0);
            ERROR_CHECK(sendRet, -1, "send path");
            return queryRet;
        }
        else{
            //非法路径
            //flag[0] = 'u';
            send(sockFd, flag, 1, 0);
            return curDirID;
        }
    }

    return queryRet;
}

